/*
 * interrupts.c
 *
 * Created: 5/21/2011 8:36:08 PM
 *  Author: X-Ravin
 */ 

#include "kernel.h"
#include "isr_vectors.h"

ISR(USART1_RX_vect)
{
	if(isr[USART1_owner] != 0)
		handleISR(USART1_RX_address, isr[USART1_owner]);
}

ISR(USART0_RX_vect)
{
	handleISR(USART0_RX_address, isr[USART0_owner]);
}

ISR(TIMER1_OVF_vect)
{
	handleISR(TIMER1_OVF_address, isr[TIMER1_owner]);
}

ISR(TIMER2_OVF_vect)
{
	handleISR(TIMER2_OVF_address, isr[TIMER2_owner]);
}


void handleISR(const int address, char owner)
{
	int vector;
	char hi,lo;

	stopScheduler();	

	vector = program[process[owner].program].offset_address + address;
	hi = vector >> 8;
	lo = vector & 0x00FF;
	//SP = process[isr.usart1].stack_pointer;
	asm volatile("mov r30, %0\n\t"
				 "mov r31, %1\n\t"
				 "icall\n\t"
				 :
				 : "r" (lo),"r" (hi));

	//SP = process[current_proc].stack_pointer;
	startScheduler();
}

inline void stopScheduler(void)
{
	TCCR0B &= 0xF8;
}

inline void startScheduler(void)
{
	TCCR0B |= 0x02;
}
